<template>
  <section>
    <!-- 工具条 高级查询 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="onsale">服务上线</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale">服务下线</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="销量" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: red">已下线</span>
          <span v-else style="color: green">已上线</span>
        </template>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button :disabled="scope.row.state===1" size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button :disabled="scope.row.state===1" type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next"
                     background
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="resources" label="图片">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="服务简介" prop="intro">
          <quill-editor  v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config.js';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      //1.分页查询的相关参数
      products: [],
      pageSize: 5,
      currentPage: 1,
      totals: 0,
      listLoading: false,

      //2.高级查询的相关参数
      keyword: "",
      //3.批量删除的相关数据
      sels: [],

      //4.添加或修改相关数据
      title: '',
      saveFormVisible: false,//对话框界面是否显示
      saveLoading: false,//保存的加载框
      saveFormRules: {
        name: [
          {required: true, message: '请输入服务名称', trigger: 'blur'}
        ]
      },
      //添加或修改界面数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        resources: '',
        productDetail:{  //与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      },
      //文件上传相关数据
      fileList: [],
      quillOption: quillConfig,
    }
  },
  methods: {
    //1.获取服务列表
    getproducts() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true; //显示加载框
      this.$http.post("/product", para).then(res => {
        this.products = res.data.data;
        this.totals = res.data.totals;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试!!!");
      })
    },
    //2.分页实现
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getproducts();
    },
    //3.高级查询实现
    keywordQuery() {
      this.currentPage = 1;
      this.getproducts();
    },
    //4.删除功能实现
    handleDel: function (index, row) {
      //elementUI提供的模态框 - 点击确认执行then里面的代码，取消执行catch
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/product/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("删除成功");
            //删除成功后对当前页的处理
            var totalPage = Math.ceil(this.totals/this.pageSize);//总页数-最后一页
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getproducts();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!![500]")
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![404]")
        })
      }).catch(() => {

      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //5.批量删除
    batchRemove: function () {
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.patch("/product", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.$message.success("删除成功");
            var totalPage = Math.ceil(this.totals/this.pageSize);//总页数-最后一页
            if(this.currentPage==totalPage && (this.totals-ids.length)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getproducts();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]");
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {

      });
    },
    //7.点击修改按钮弹出对话框
    handleEdit: function (index, row) {
      this.title = "修改";
      this.saveFormVisible = true;//弹出对话框
      //回显数据：创建一个空对象{}，将row中的数据拷贝给{}
      this.saveForm = Object.assign({}, row);

      //处理fileList
      this.fileList=[];
      if (this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i=0;i<arr.length;i++){
          var url = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    //8.点击新增按钮弹出对话框
    handleAdd: function () {
      this.title = "新增";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        resources: '',
        productDetail:{  //与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      };
      //清空fileList
      this.fileList=[];
    },
    //9.新增或修改数据提交到后端
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            this.$http.put("/product", para).then(res => {
              this.saveLoading = false;//关闭加载框
              this.saveFormVisible = false;//关闭对话框
              if (res.data.success) { //操作成功
                this.$message.success("操作成功");
                this.getproducts();
              } else { //操作失败
                this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
                this.saveLoading = false;//关闭加载框
                this.saveFormVisible = false;//关闭对话框
              }
            }).catch(res => {
              this.$message.error("系统繁忙，请稍后重试!!![400,404]");
              this.saveLoading = false;//关闭加载框
              this.saveFormVisible = false;//关闭对话框
            })
          });
        }
      });
    },

    //文件上传的业务逻辑
    handleSuccess(response, file, fileList){
      var url = response.resultObj;
      //处理resources
      if(this.saveForm.resources){
        this.saveForm.resources = this.saveForm.resources+","+url;
      }else {
        this.saveForm.resources = url;
      }
      //处理fileList
      this.fileList=[];
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(let i = 0;i < arr.length;i++){
          var url = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      console.log(file);
      var filePath =file.url;
      filePath = filePath.substring(filePath.indexOf("/group1"));
      //1.在文件服务器中删除该图片
      this.$http.delete("/fastDfs?path="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            }else{
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
      //2.处理resources
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(let i=0; i<arr.length;i++){
          var url=arr[i];
          if(url == filePath){
            arr.splice(i,1);
            break;
          }
        }
        this.saveForm.resources = arr.join(",");
      }
      //3.处理fileList
      this.fileList=[];
      if (this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i=0;i<arr.length;i++){
          var url = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }


    },
    //图片预览
    handlePreview(file) {
      console.log(file);
    },
    //服务上线
    onsale(){
      if(this.sels.length<1){
        this.$message.warning("请先选中需要上线的服务！！！");
        return ;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认上线选中的服务吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/product/onsale", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.$message.success("上线成功");
            this.getproducts();
          } else { //操作失败
            this.$message.error(res.data.msg);
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {

      });
    },
    //服务下线
    offsale(){
      if(this.sels.length<1){
        this.$message.warning("请先选中需要下线的服务！！！");
        return ;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认下线选中的服务吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/product/offsale", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.$message.success("下线成功");
            this.getproducts();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]");
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {

      });
    },

  },
  mounted() {
    this.getproducts();
  }
}

</script>

<style scoped>

</style>